package com.mercury.controller;

import com.mercury.model.User;
import com.mercury.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author ：tx
 * @description：
 * @date ：Created in 2019/1/26 17:18
 * @modified By：
 * @version:
 */
@Controller
@RequestMapping("/user")
public class UserController {

    UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/findUsers",method = RequestMethod.GET)
    public String findUsers(Model model){
        List<User> userList = userService.findUsers(Long.MAX_VALUE,20);
        model.addAttribute("userList",userList);
        return "findUsersView";
    }


    @RequestMapping(value = "/getUsers",method = RequestMethod.GET)
    public List<User> getUsers(){
        List<User> userList = userService.findUsers(Long.MAX_VALUE,20);
        return userList;
    }


    @RequestMapping(value = "/saveUser",method = RequestMethod.GET)
    public String saveUser(User user){
        userService.saveUser(user);
        userService.add(1);
        return "redirect:/user/saveUserView/"+user.getUserName();
    }

    @RequestMapping(value = "/saveUserView/{userName}")
    public String showSaveUsers(@PathVariable("userName") String name,Model model){
        User user = userService.findUser(name);
        model.addAttribute(user);
        return "saveUserView";
    }

    @RequestMapping(value = "/findByPathParam",method = RequestMethod.POST)
    public String findByPathPatam(@RequestParam("userName") String name){
        User user = userService.findUser(name);
        return "findByPathPatamView";
    }

    @RequestMapping(value = "/deliverValidateParam",method = RequestMethod.GET)
    public String deliverValidateParam(@Validated  User uesr, Errors errors){
        if(errors.hasErrors()){
            return "error";
        }
        return "deliverValidateParamView";
    }
}

